package com.kzd.sdk.callback;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.kzd.sdk.entity.KZD_BaseResponseAny;
import com.kzd.sdk.error.KZD_CustomException;
import com.kzd.sdk.utils.ExceptionUtils;
import com.lzy.okgo.callback.AbsCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;

import okhttp3.ResponseBody;

public abstract class KZD_JsonCallbackAny<T> extends AbsCallback<KZD_BaseResponseAny<T>> {

    private final Class<T> tClass;

    public KZD_JsonCallbackAny(Class<T> tClass) {
        this.tClass = tClass;
    }

    @Override
    public KZD_BaseResponseAny<T> convertResponse(okhttp3.Response response) throws Throwable {
        ResponseBody body = response.body();
        if (body == null)
            throw new KZD_CustomException("body is null",1000);
        String bodyStr = body.string();
        if (bodyStr == null || bodyStr.length() == 0)
            throw new KZD_CustomException("body is null",1000);
        Gson mGson = new Gson();
        KZD_BaseResponseAny<T> responseAny = mGson
                .fromJson(bodyStr, new TypeToken<KZD_BaseResponseAny<T>>() {
                }.getType());
        T data = null;
        if (responseAny.getCode() == 1) {
            data = mGson.fromJson(mGson.toJson(responseAny.getData()), tClass);
        } else {
            throw new KZD_CustomException(responseAny.getMessage(),responseAny.getCode());
        }
        responseAny.setData(data);

//        KZD_BaseResponseAny<T> data =
//                JSON.parseObject(body.string(),new TypeReference<KZD_BaseResponseAny<T>>(tClass){});
//        if (data.getCode() != 1) {
//            throw new KZD_CustomException(data.getMessage());
//        }
        return responseAny;
    }

    @Override
    public void onStart(Request<KZD_BaseResponseAny<T>, ? extends Request> request) {
        super.onStart(request);
        onStart();
    }

    @Override
    public void onSuccess(Response<KZD_BaseResponseAny<T>> response) {
        T data = response.body().getData();
        if (data == null) {
            return;
        }
        onSuccess(data);
    }

    @Override
    public void onError(Response<KZD_BaseResponseAny<T>> response) {
        super.onError(response);
        onError(ExceptionUtils.getMessage(response.getException()));
    }


    public void onStart() {
    }

    public void onSuccess(T data) {
    }

    public void onError(String message) {
    }
}
